package br.com.util;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;

public class PropertiesUtil {
	
	private static final String APPLICATION_MESSAGES = "/ValidationMessages_pt_BR.properties";
	private static final String VERSION = "/version.properties";
	private static PropertiesUtil instance;
	private Properties propsVersion;
	private Properties propsApplicationMessages;

	private PropertiesUtil(){
		try{
			
			/** PROPS APPLICATIONMESSAGES **/
			propsApplicationMessages = new Properties();
			propsApplicationMessages.load(this.getClass().getResourceAsStream(APPLICATION_MESSAGES));
			
			/** CONTROLE VERSAO **/
			propsVersion = new Properties();
			propsVersion.load(this.getClass().getResourceAsStream(VERSION));
			
		}catch(Exception ex){
			String msg = "Não foi possível ler o arquivo de configuração. \nDetalhe: " + ex.getMessage();
			throw new RuntimeException(msg);
		}
	}
	
	
	public void newKeyPropsApplicationMessages(String chave, String value, String comentario){
		 try {
			 
			 File file = new File("src//ValidationMessages_pt_BR.properties");
			 FileOutputStream fos = new FileOutputStream(file, true);
			 String linha = "";
			 
			 /** COMENTARIO **/
			 if (comentario != null) {
				  
				  linha = "\n# ........................................................................." + "\n";	
				  fos.write(linha.getBytes());   
				 
				  linha = "# " + comentario + "\n";	
				  fos.write(linha.getBytes()); 
				  
				  linha = "# ........................................................................." + "\n";	
				  fos.write(linha.getBytes());   
				  
			 }
			 
			 /** CHAVES **/			 
			 linha = chave + "="+ value + "\n";    
	         fos.write(linha.getBytes());    
	       
	         fos.close(); 		 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String getChavePropsApplicationMessages(String chave){
		return propsApplicationMessages.getProperty(chave);
	}
	
	public static PropertiesUtil getInstance(){
		if(instance == null){
			instance = new PropertiesUtil();
		}
		return instance;
	}
	
	public static String getMessageChave(String chave){
		return getInstance().getChavePropsApplicationMessages(chave);
	}
	
	/** Retorna versão a partir do arquivo version.properties **/
	public String getVersao(String chave){
		return propsVersion.getProperty(chave);
	}
	
	public static String getVersaoChave(String chave){
		return getInstance().getVersao(chave);
	}
	
}
